package org.tabletopmachine.basics;

import de.matthiasmann.twl.Event;
import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.ThemeInfo;
import de.matthiasmann.twl.Widget;
import de.matthiasmann.twl.renderer.Image;
import de.matthiasmann.twl.ParameterMap;

import java.util.Random;

public class Die extends Widget {
	private static final Random rndGen = new Random();
	private ParameterMap _dieImages;
	private Integer _value;
	private boolean _allowReRoll;
	private Image _dieImage;

	public Die() {
		_value = null;
		_allowReRoll = false;
	}

	public void roll() {
		if (_value == null || _allowReRoll) {
			_value = rndGen.nextInt(6) + 1;
			findIcon();
			if (_allowReRoll)
				_allowReRoll = false;
		}
	}

	public boolean isReRollAllowed() {
		return _allowReRoll;
	}

	public void allowReRoll() {
		_allowReRoll = true;
	}

	public void disallowReRoll() {
		_allowReRoll = false;
	}

	public Integer getValue() {
		return _value;
	}

	@Override
	protected void applyTheme(ThemeInfo themeInfo) {
		super.applyTheme(themeInfo);
		_dieImages = themeInfo.getParameterMap("dieimages");
		findIcon();
	}

	private void findIcon() {
		if (_dieImages == null)
			_dieImage = null;
		else if (_value == null)
			_dieImage = _dieImages.getImage("0");
		else
			_dieImage = _dieImages.getImage("" + _value);
	}

	@Override
	protected void layout() {

		super.layout();
		setInnerSize(18, 18);
		setSize(18, 18);
		adjustSize();
	}

	@Override
	protected void paintWidget(GUI gui) {
		if (_dieImage != null) {
			_dieImage.draw(getAnimationState(), getInnerX(), getInnerY(), 16, 16);
		}
	}

	@Override
	protected boolean handleEvent(Event evt) {
		if (evt.isMouseEventNoWheel()) {
			if (evt.getMouseButton() == Event.MOUSE_LBUTTON) {
				roll();
			}
		}
		return super.handleEvent(evt);
	}
}
